﻿using System.Collections;
using System.Windows;
using System.Windows.Controls;

namespace DynamicGeometry
{
    public class ComboboxPropertyEditor : LabeledPropertyEditor, IPropertyEditor
    {
        public ComboBox ComboBox { get; set; }

        protected override UIElement CreateEditor()
        {
            ComboBox = new ComboBox();
            ComboBox.VerticalAlignment = VerticalAlignment.Center;
            ComboBox.SelectionChanged += ComboBox_SelectionChanged;
            return ComboBox;
        }

        protected bool guard = false;
        void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (guard)
            {
                return;
            }
            SetValue(ComboBox.SelectedItem);
        }

        public IEnumerable Items { get; set; }

        public virtual void Init()
        {
            guard = true;
            FillList();
            UpdateSelectedItem();
            guard = false;
        }

        public virtual void FillList()
        {
            ComboBox.Items.Clear();
            foreach (var item in Items)
            {
                ComboBox.Items.Add(item);
            }
        }

        public virtual void UpdateSelectedItem()
        {
            var value = Property.GetValue(Target, null);
            foreach (var item in Items)
            {
                if (item.Equals(value))
                {
                    ComboBox.SelectedItem = item;
                }
            }
        }
    }
}
